import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 添加响应拦截器，正确提取后端错误消息
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    // 尝试从错误响应中提取详细错误信息
    if (error.response && error.response.data) {
      const errorData = error.response.data
      
      // 如果后端返回了具体的错误消息，使用它
      if (typeof errorData === 'string' && errorData.trim() !== '') {
        error.message = errorData
      } else if (errorData.message) {
        error.message = errorData.message
      } else if (errorData.error) {
        error.message = errorData.error
      }
      // 如果是Spring Boot的默认错误格式
      else if (errorData.path && errorData.status) {
        error.message = errorData.message || '请求失败'
      }
    }
    
    return Promise.reject(error)
  }
)

export const movieService = {
  async getAllMovies() {
    const res = await api.get('/movies')
    return res.data
  },

  async getMovie(id) {
    const res = await api.get(`/movies/${id}`)
    return res.data
  },

  async getSeats(movieId) {
    const res = await api.get(`/movies/${movieId}/seats`)
    return res.data
  },

  async buyTicket(movieId, seatNumber, buyerName) {
    const res = await api.post('/tickets/buy', {
      movieId,
      seatNumber,
      buyerName
    })
    return res.data
  },

  async buyTicketsBatch(movieId, seatNumbers, buyerName) {
    const res = await api.post('/tickets/buy-batch', {
      movieId,
      seatNumbers,
      buyerName
    })
    return res.data
  }
}

export default api